import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Tag, Space, Spin, message, Button, Modal, Form, Input, Select, Popconfirm, Typography, Tooltip, Divider } from 'antd';
import { 
  ArrowLeftOutlined, 
  PlusOutlined, 
  DeleteOutlined, 
  EditOutlined, 
  SwapOutlined,
  BookOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { TableCard } from '@/components/common';
import { contestService } from '@/services/contestService';
import { problemService } from '@/services/problemService';
import { Problem } from '@/types/problem';
import { Contest } from '@/types/contest';

const { Title, Text } = Typography;

const Problems: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [contest, setContest] = useState<Contest | null>(null);
  const [problems, setProblems] = useState<Problem[]>([]);
  const [addProblemModalVisible, setAddProblemModalVisible] = useState(false);
  const [addExistingProblemModalVisible, setAddExistingProblemModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [existingProblemForm] = Form.useForm();

  useEffect(() => {
    if (id) {
      fetchContest();
      fetchProblems();
    }
  }, [id]);

  const fetchContest = async () => {
    try {
      setLoading(true);
      const response = await contestService.getContest(Number(id));
      setContest(response.data.data);
    } catch (error) {
      message.error('获取比赛详情失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchProblems = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await problemService.getProblems({ contest_id: Number(id) });
      setProblems(response.data.data.results || []);
    } catch (error) {
      message.error('获取比赛题目失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteProblem = async (problemId: number) => {
    try {
      await problemService.deleteProblem(problemId);
      message.success('删除题目成功');
      fetchProblems();
    } catch (error) {
      message.error('删除题目失败');
    }
  };

  const handleEditProblem = (problemId: number) => {
    // 导航到题目编辑页面，并传入contest_id参数
    navigate(`/admin/problem/edit/${problemId}?contest_id=${id}`);
  };

  const handleAddExistingProblem = async (values: any) => {
    try {
      await problemService.convertToContestProblem(Number(id), values.problem_id);
      message.success('添加已有题目成功');
      setAddExistingProblemModalVisible(false);
      existingProblemForm.resetFields();
      fetchProblems();
    } catch (error: any) {
      if (error.response?.data?.message === "该题目已经是比赛题目") {
        message.error('该题目已经是比赛题目');
      } else if (error.response?.data?.message === "比赛题目添加失败，请检查比赛ID是否正确") {
        message.error('比赛题目添加失败，请检查比赛ID是否正确');
      } else {
        message.error('添加已有题目失败');
      }
    }
  };

  const handleConvertToRegular = (problemId: number) => {
    message.info('功能开发中！');
  };

  const columns = [
    {
      title: '题目ID',
      dataIndex: '_id',
      key: '_id',
      width: 100,
      render: (text: string) => (
        <Tag color="blue" style={{ margin: 0, padding: '2px 8px' }}>
          {text}
        </Tag>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <Text strong>{text}</Text>
        </Tooltip>
      ),
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 120,
      render: (difficulty: string) => {
        const colorMap = {
                  'Low': 'green',
        'Mid': 'orange',
        'High': 'red'
        };
        return (
          <Tag color={colorMap[difficulty as keyof typeof colorMap]} style={{ margin: 0, padding: '2px 8px' }}>
            {difficulty}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      render: (_: any, record: Problem) => (
        <Space size="small">
          <Tooltip title="编辑题目">
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => handleEditProblem(record.id)}
              size="small"
            >
              编辑
            </Button>
          </Tooltip>
          <Tooltip title="转为普通题目">
            <Button 
              type="default" 
              icon={<SwapOutlined />}
              onClick={() => handleConvertToRegular(record.id)}
              size="small"
              disabled
            >
              转为普通
            </Button>
          </Tooltip>
          <Popconfirm
            title="确定要删除这个题目吗？"
            description="删除后将无法恢复，请谨慎操作！"
            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
            onConfirm={() => handleDeleteProblem(record.id)}
            okText="确定"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Tooltip title="删除题目">
              <Button type="primary" danger icon={<DeleteOutlined />} size="small">
                删除
              </Button>
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  if (loading && !problems.length) {
    return (
      <div style={{ padding: '64px', textAlign: 'center' }}>
        <Spin size="large" />
        <div style={{ marginTop: 8 }}>加载中...</div>
      </div>
    );
  }

  return (
    <div>
      <TableCard 
        title={contest ? `《${contest.title}》题目管理` : '题目管理'}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => navigate(`/admin/problem/create?contest_id=${id}`)}
            >
              创建比赛题目
            </Button>
            <Button 
              type="default"
              icon={<PlusOutlined />}
              onClick={() => setAddExistingProblemModalVisible(true)}
            >
              添加已有题目
            </Button>
            <Button 
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate(`/admin/contest/${id}`)}
            >
              返回比赛
            </Button>
          </Space>
        }
        tableProps={{
          columns: columns,
          dataSource: problems,
          loading: loading,
          rowKey: 'id',
          pagination: false,
        }}
      />

      {/* 添加已有题目对话框 */}
      <Modal
        title="添加已有题目"
        open={addExistingProblemModalVisible}
        onOk={() => existingProblemForm.submit()}
        onCancel={() => {
          setAddExistingProblemModalVisible(false);
          existingProblemForm.resetFields();
        }}
        okText="添加"
        cancelText="取消"
      >
        <Form 
          form={existingProblemForm}
          onFinish={handleAddExistingProblem}
          layout="vertical"
        >
          <Form.Item
            name="problem_id"
            label="题目ID"
            rules={[
              { required: true, message: '请输入题目ID' }
            ]}
          >
            <Input 
              placeholder="请输入要添加的题目ID" 
            />
          </Form.Item>
        </Form>
      </Modal>

    </div>
  );
};

export default Problems; 